<template>
  <!-- 实验报告统计 -->
  <div id="atten-details">
    <div class="preview-top">
      <div class="preview-top1">
        <div class="preview-top-content">
          <div>
            <span class="preview-title">{{ classData.courseName }}</span>
            <span class="preview-line"></span>
            <span style="margin-right:10px;">{{ classData.name }}</span>
            <span>{{ classData.grade }}</span>
          </div>
        </div>
      </div>
    </div>
    <div class="jx-content">
      <div class="search-box fl" style="width:100%;">
        <el-form :inline="true" @submit.native.prevent>
          <el-form-item label="学生信息 :">
            <el-input v-model="userInfo" placeholder="请输入学号或姓名"></el-input>
          </el-form-item>
          <el-form-item>
            <div class="button-style" @click="getList">搜 索</div>
          </el-form-item>
          <el-form-item class="fr">
              <div class="download-style" @click="downloads">数据下载</div>
          </el-form-item>
        </el-form>
      </div>
      <el-table v-loading="tableLoading" :data="list" style="width: 100%">
        <el-table-column type="index" width="55" label="序号"></el-table-column>
        <el-table-column prop="userName" label="学生姓名"></el-table-column>
        <el-table-column prop="userNumber" label="学生学号"></el-table-column>
        <el-table-column label="提交次数">
          <template slot-scope="scope">
            <div class="ts-c-blue">{{ scope.row.reportSubmittedNum }}</div>
          </template>
        </el-table-column>
        <el-table-column label="平均分值">
          <template slot-scope="scope">
            <div>平均值{{ scope.row.avgReportScore }}</div>
          </template>
        </el-table-column>
        <el-table-column label="得分详情">
          <template slot-scope="scope">
            <a class="ts-c-blue ts-c-xq" @click="getListDetails(scope.row)" href="javascript:;">详情</a>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 弹窗 -->
    <el-dialog @close="closeDialog" :close-on-click-modal="false" class="dialog-virtual" :title="`${userDetails.row.userName}实验报告详情`" :visible.sync="userDetails.dialog" width="850px">
        <div class="dialog-content">
          <el-table v-loading="tableLoading" :data="userDetails.data.content" style="width: 100%">
            <el-table-column width="55" label="序号">
              <template slot-scope="scope"><span>{{scope.$index+(userDetails.pageNum - 1) * userDetails.pageSize + 1}}</span> </template>
            </el-table-column>
            <el-table-column prop="name" label="章节名称">
              <template slot-scope="scope">
                <div v-if="scope.row.opened" :title="scope.row.name">{{ scope.row.name }}</div>
                <div v-else :title="scope.row.name">{{ scope.row.name }}（未公开）</div>
              </template>
            </el-table-column>
            <el-table-column prop="reportStatusStr" label="状态" width="80"></el-table-column>
            <el-table-column label="分数" width="80">
              <template slot-scope="scope">
                <div v-if="scope.row.reportScore !== undefined" class="ts-c-blue">{{ scope.row.reportScore }}</div>
                <div v-else class="ts-c-blue">-</div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <span class="dialog-footer" v-if="userDetails.data">
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="userDetails.data.pageNum" :page-size="userDetails.data.pageSize" :total="userDetails.data.total" layout="total, prev, pager, next, jumper"></el-pagination>
        </span>
    </el-dialog>
  </div>
</template>
<script>
import axios from "axios";
import $ from "jquery";
export default {
  data() {
    return {
      classId: this.$route.query.classId,
      courseId: this.$route.query.courseId,
      userInfo: '',
      userDetails:{
        userName:'',
        dialog:false,
        pageNum:1,
        pageSize:10,
        tableLoading:'',
        row:'',
        data:'',
      },
      list: [],
      tableLoading: "",
      classData:{
        courseName:'',
        grade:'',
        //班级名称
        name:'',
      },
    };
  },
  created() {},
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.getCourseName();
      this.getClassName();
      this.getList();
    },
    //获取课程名称
    getCourseName() {
      let self = this;
      let courseId = self.courseId;
      self.$http
        .get(`/tes/course/${courseId}/chapter/0`)
        .then((response) => {
          let res = response.data;
          if (res.code == "200") {
            console.log(res,223);
            self.classData.courseName = res.data.courseName;
          } else{
            self.$message.error(res.message)
          }
        })
        .catch((err) => {
          self.$message.error(err.message);
        });
    },
    //获取班级和年级名称
    getClassName() {
      let self = this;
      let classId = self.classId;
      self.$http
        .get(`/tes/course/class/${classId}`)
        .then((response) => {
          let res = response.data;
          if (res.code == "200") {
            self.classData.grade = res.data.grade;
            self.classData.name = res.data.name;
          } else{
            self.$message.error(res.message)
          }
        })
        .catch((err) => {
          self.$message.error(err.message);
        });
    },
    //获取列表数据
    getList() {
      let self = this;
      let classId = self.classId;
      let courseId = self.courseId;
      self.$http.post(`/tes/statistic/course/${courseId}/class/${classId}/task`,{
        userInfo:self.userInfo,
      }).then((response) => {
          let res = response.data;
          if (res.code == "200") {
            console.log(res,22423);
            self.list = res.data;
          }else if(res.code == '404'){
            self.list = [];
            self.$message.error(res.message)
          }else{
            self.$message.error(res.message)
          }
        })
        .catch((err) => {
          self.$message.error(err.message);
        });
    },
    //获取列表详情数据
    getListDetails(row) {
      let self = this;
      let courseId = self.courseId;
      let classId = self.classId;
      let userId = row.userId;
      let pageNum = self.userDetails.pageNum;
      let pageSize = self.userDetails.pageSize;
      self.userDetails.row = row;
      self.$http.get(`/tes/statistic/course/${courseId}/class/${classId}/task/${userId}?pageNum=${pageNum}&pageSize=${pageSize}`)
      .then((response) => {
        let res = response.data;
        if (res.code == "200") {
          console.log(res,22423);
          self.userDetails.data = res.data;
          self.userDetails.dialog = true;
        } else{
          self.$message.error(res.message)
        }
      })
      .catch((err) => {
        self.$message.error(res.message);
      });
    },
    closeDialog(){
      this.userDetails.pageNum = 1;
    },
    handleSizeChange() {},
    //翻页
    handleCurrentChange(val) {
      this.userDetails.pageNum = val;
      this.getListDetails(this.userDetails.row);
    },
    //数据下载
    downloads(){
      //post
      ///statistic/course/{courseId}/class/{classId}/task/download
      let self = this
        let courseId = self.courseId;
        let classId = self.classId;
        let userInfo = self.userInfo;
        let className = self.classData.name;
        self.downloadStatus = true
        self.downloadText = '下载中'
        self.$http.post(`/tes/statistic/course/${courseId}/class/${classId}/task/download`,{
          userInfo:userInfo
        },{responseType: 'blob'}) .then((response) => {
            let contentType = response.headers["content-type"]
            if (contentType == "application/json;charset=UTF-8") {
                let codeMessage = response.headers["code-message"];
                console.log(codeMessage);
                let str = '';
                if(codeMessage == 404){
                    str = '暂无统计';
                }
                if(codeMessage == 500){
                    str = '服务器内部错误';
                }
                if(codeMessage == 600100){
                    str = '当前班级正在统计中，请稍后再试';
                }
                self.$message.error(str);
            }else{
              let blob = new Blob([response.data], {type: response.headers['content-disposition']});
              let url = window.URL.createObjectURL(blob);
              //let fileName = response.headers['content-disposition'].split(";")[1].split("filename=")[1];
              let fileName = `${className}班级的实验报告统计.xls`;
              let downloadElement = document.createElement('a');
              downloadElement.style.display = 'none';
              downloadElement.href = url;
              downloadElement.download = fileName; //下载后文件名
              document.body.appendChild(downloadElement);
              downloadElement.click(); //点击下载
              document.body.removeChild(downloadElement); //下载完成移除元素
              window.URL.revokeObjectURL(url);
              self.downloadStatus = false
              self.downloadText = ''
            }
        }).catch(err => {
            console.log(err)
        })
    },
  },
};
</script>
<style lang="scss" scoped>
@import "../../../styles/img-init";
</style>
<style lang="scss">
@import "../../../styles/layout/color_variables";
#atten-details.isCreativeCourse {
  margin: 20px auto 30px;
}
#atten-details {
  box-shadow: 0px 0px 0px;
  border-radius: none;
  img {
    max-width: 80%;
  }
  .preview-top {
    position: relative;
    z-index: 1;
    height: 80px;
    margin: 0px auto 0;
    .preview-top1 {
      width: 100%;
      height: 60px;
      line-height: 60px;
      background: #101937;
      position: fixed;
      top: 0;
      color: #fff;
      font-size: 14px;
      .preview-top-content {
        width: 1200px;
        margin: 0 auto;
        span {
          margin-right: 40px;
        }
        .preview-title {
          font-size: 18px;
          margin-right: 0;
        }
        .preview-line {
          margin: 0 6px;
        }
      }
    }
  }
}
</style>
